const express = require('express');
const mongoose = require('mongoose');
const UserModel = require('../model/UserModel')

let apiRouter = express.Router();

apiRouter.get('/', (req, res) => {
    res.render('home');
})

apiRouter.get('/control',(req,res)=>{
    res.render('control');
})

apiRouter.get('/findAll',(req,res)=>{
    UserModel.find({})
    .then((res2) => {
        if(res2){
            res.send({
                info: res2
            });
        }
        else{
            res.send({
                info:'failed'
            })
        }
    }).catch((err) => {
        res.send({
            info: err
        });
    })
})

apiRouter.post('/register', (req, res) => {
    console.log(req.body);

    // 也可以通过create({xxx})新增一条数据
    UserModel.insertMany([{
        name: req.body.name,
        age: req.body.age,
        password: req.body.password
    }]).then(() => {
        res.send({
            info: 'success'
        })
    }).catch((err) => {
        res.send({
            info: err
        })
    })
});

apiRouter.post('/login', (req, res) => {
    const {
        name,
        age,
        password
    } = req.body;
    UserModel.findOne({
        name,
        age,
        password
    }).then((res2) => {
        if(res2){
            res.send({
                info: res2
            });
        }
        else{
            res.send({
                info:'请检查信息输入是否正确。'
            })
        }
    }).catch((err) => {
        res.send({
            info: err
        });
    })
})

module.exports = apiRouter;